<template>
  <v-dialog v-model="dialog" persistent transition="fab-transition" max-width="1000">
    <Feedback :isSuccess="isSuccess" :isError="isError" :text="text"></Feedback>
    <v-card>
      <div class="d-flex justify-space-between mb-5" id="modal-header">
        <v-card-title class="py-3">上传视频</v-card-title>
        <div class="mt-3 mr-2">
          <v-btn text>
            上传
          </v-btn>
          <v-btn icon text @click="closeModal">
            <v-icon>mdi-close</v-icon>
          </v-btn>
        </div>
      </div>

      <v-card-text v-if="!uploaded"
        class="d-flex flex-column align-center my-md-12 py-md-12 my-sm-8 py-sm-8 my-xs-0 py-xs-0 my-12 py-12">
        <div v-if="!uploading" class="text-center">
          <div>
            <v-btn icon class="grey lighten-2 mb-4" style="height: 104px;width: 104px;" @click="selectFile"><v-icon
                x-large class="grey--text text--darken-1">mdi-upload</v-icon></v-btn>
          </div>

          <ValidationProvider rules="required" v-slot="{ errors }" name="file" ref="provider">
            <v-file-input @change="uploadVideo" v-model="selectedFile" accept="video/mp4" placeholder="选择要上传的视频"
              prepend-icon="mdi-video" :error-messages="errors" ref="fileInput"></v-file-input>
          </ValidationProvider>
          <v-btn type="submit" depressed @click="$refs.fileInput.$refs.input.click()"
            class="blue darken-3 flat white--text mt-4">选择文件</v-btn>
        </div>
        <v-progress-circular v-else :rotate="360" :size="100" :width="15" :value="value" color="teal">
          {{ value }}
        </v-progress-circular>
        <span v-if="value==100">客户端上传成功，正在等待服务器解析...</span>
      </v-card-text>
      <v-card-text v-else>
        <h2 class="mb-6">详情</h2>
        <v-row>
          <v-col order="last" order-sm="last" order-md="first" order-lg="first" order-xl="first" cols="12" sm="12"
            md="8" lg="8">
            <ValidationObserver ref="form">
              <form >
                <ValidationProvider v-slot="{ errors }" name="标题" rules="required|min:3">
                  <v-text-field v-model="formData.title" :error-messages="errors" label="标题（必须)" class="mb-3" filled
                    dense counter="100" max-length="100"></v-text-field>
                </ValidationProvider>
                <ValidationProvider v-slot="{ errors }" name="简介" rules="required|min:3">
                  <v-textarea filled auto-grow :error-messages="errors" label="简介" placeholder="简单介绍一下你的视频" rows="5"
                    counter="5000" max-length="5000" v-model="formData.overview" row-height="20"></v-textarea>
                </ValidationProvider>
                <!-- <ValidationProvider
                  v-slot="{ errors }"
                  name="Visibilty"
                  rules="required|min:3"
                >
                  <v-select
                    :items="visibilty"
                    :error-messages="errors"
                    filled
                    label="Visibilty"
                    v-model="formData.visibilty"
                  ></v-select>
                </ValidationProvider>
                <ValidationProvider
                  v-slot="{ errors }"
                  name="Cateogry"
                  rules="required|min:3"
                >
                  <v-select
                    :items="categoriesTitles"
                    :error-messages="errors"
                    filled
                    label="Categories"
                    v-model="formData.category"
                    :loading="categoryLoading"
                  ></v-select>
                </ValidationProvider> -->

                <div class="mt-6 d-flex justify-space-between">
                  <v-btn :loading="submitLoading" @click="post" class="primary" depressed>提交</v-btn>
                </div>
              </form>
            </ValidationObserver>
          </v-col>
          <v-col order-sm="1" cols="12" sm="12" md="4" lg="4" class="text-center">
            <v-btn text @click="toggleShow">修改封面</v-btn>
            <div v-if="show">
              <v-file-input v-model="selectedCover" label="选择文件" placeholder="没有选择文件" accept="image/png,image/jpeg"></v-file-input>
              <v-btn @click="uploadCover">上传</v-btn>
              <p v-if="uploadProgress !== null">上传进度: {{ uploadProgress }}%</p>
              <p v-if="successMessage">{{ successMessage }}</p>
            </div>
            <v-responsive width="330" class="mx-auto">
              <div v-if="!imgDataUrl" class="px-12" id="image-placeholder">
                <v-icon>mdi-image-plus</v-icon>
              </div>
              <v-img v-else max-width="330" height="350" :src="imgDataUrl"></v-img>
            </v-responsive>
          </v-col>
        </v-row>
      </v-card-text>
      <v-card-actions v-if="!uploaded">
        <p class="text-center grey--text caption px-12 px-xs-0">
          一旦视频提交到EchoVivid，就代表你会严格遵守EchoVivid的视频社区规则
        </p>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

<script>
import axios from "axios";
import { mergeVideoInfo } from "../services/VideoRequest";
import Feedback from "./Feedback.vue";
export default {
  name: "UploadModal",
  props: ["openDialog"],
  data: function () {
    return {
      isSuccess:false,
      isError:false,
      text:'服务器异常',
      mergedVideo:{},
      // dialog: this.openDialog ? this.openDialog : false,
      selectedCover: null,
      uploadProgress:null,
      successMessage:null,
      valid: false,
      uploaded: false,
      uploading: false,
      submitLoading: false,
      categoryLoading: false,
      interval: {},
      value: 0,
      show: false,
      rules: [
        (value) =>
          !value ||
          value.size > 1000000000 ||
          `视频必须小于1GB!, ${value.size}`,
      ],
      categoriesTitles: [],
      categories: [],
      visibilty: ["Public", "Private"],
      selectedFile: [],
      formData: {
        id: "",
        title: "",
        description: "",
        category: "",
        visibilty: "",
      },
      imgDataUrl: "",
      url: "",
      headers: { Authorization: `Bearer ${this.$store.getters.getToken}` },
    };
  },
  computed: {
    dialog() {
      return this.openDialog;
    },
  },
  methods: {
    async uploadVideo(e) {
      const { valid } = await this.$refs.provider.validate(e);

      if (!valid) return;
      // console.log(this.selectedFile)

      this.uploading = true;
      const fd = new FormData();
      fd.append("video", this.selectedFile);
      let video = await axios.post("/api/echo/video/upload", fd, {
        headers: {
          "Content-Type": "multipart/form-data",
          "Authorization": localStorage.getItem("Authorization")
        },
        onUploadProgress: progressEvent => {
          this.value = Math.round(
            (progressEvent.loaded / progressEvent.total) * 100
          );
        }
      })
        .catch((err) => {
          this.isError = true
          console.log(err)
          return
        }).finally(() => {
          this.uploaded = true;
          this.uploading = false;
        })
      if (!video) return;
      video = video.data;
      this.mergedVideo = video
      this.formData.id = video.videoId;
      this.formData.title = video.title;
      this.formData.overview = video.overview;
      //this.formData.cateogry = video.cateogry;
      this.url = video.cover;
      this.imgDataUrl = video.cover
      // this.interval = setInterval(() => {
      //   if (this.value === 100) {
      //     this.uploaded = true
      //     clearInterval(this.inte-rval)
      //   }
      //   this.value += 10
      // }, 1000)
      // }
      // }
    },
    uploadCover() {
      const formData = new FormData();
      formData.append("cover", this.selectedCover);
      axios.post("/api/echo/video/cover", formData, {
        headers: {
          "Content-Type": "multipart/form-data",
          "Authorization": localStorage.getItem("Authorization")
        },
        onUploadProgress: progressEvent => {
          this.uploadProgress = Math.round(
            (progressEvent.loaded / progressEvent.total) * 100
          );
        }
      })
        .then((res) => {
          this.successMessage = "封面上传成功!";
          this.selectedFile = null;
          this.uploadProgress = null;
          console.log(res)
          this.imgDataUrl = res.data
          this.show = false
        })
        .catch(() => {
          this.successMessage = "封面上传失败!";
          this.uploadProgress = null;
        })
    },
    async post() {
      if (this.imgDataUrl == "") return;
      this.submitLoading = true;
      // this.formData.category = this.categories.find(
      //   (category) => category.title === this.formData.category
      // )._id;
      console.log(this.mergedVideo)
      this.mergedVideo.cover = this.imgDataUrl
      this.mergedVideo.overview = this.formData.overview
      this.mergedVideo.title = this.formData.title
      const video = await mergeVideoInfo(this.mergedVideo)
        .catch((err) => {
          console.log(err);
        })
        .finally(() => {
          this.submitLoading = false;
          this.uploaded = false;
        });

      if (!video) return;
      // this.$nextTick(() => {
      //   this.$refs.form.reset()
      // })
      this.text = video.data.message
      this.isSuccess = true
      this.formData.visibilty = "";
      this.imgDataUrl = "";
      this.selectedFile = [];
      this.closeModal();

      this.$router.push(`/studio/videos`);
      // console.log('submittied')
    },
    // async getCategories() {
    //   this.categoryLoading = true;
    //   const categories = await CategoryService.getAll()
    //     .catch((err) => {
    //       console.log(err);
    //     })
    //     .finally(() => (this.categoryLoading = false));

    //   this.categoriesTitles = categories.data.data.map((category) => {
    //     return category.title;
    //   });
    //   this.categories = categories.data.data;
    // },
    closeModal() {
      this.$emit("closeDialog");
    },
    selectFile() {
      this.$refs.fileInput.$refs.input.click();
    },
    toggleShow() {
      this.show = !this.show;
    },
    cropSuccess(imgDataUrl, field) {
      console.log("-------- crop success --------");
      console.log(field);
      this.imgDataUrl = imgDataUrl;
    },
  },
  components: {
    Feedback
  },
  mounted() {
    //this.getCategories();
  },
};
</script>

<style lang="scss">
#modal-header {
  border-bottom: 1px solid rgb(238, 232, 232);
}

#image-placeholder {
  padding-top: 8em;
  padding-bottom: 8em;
  border: 2px dashed rgb(209, 209, 209);
}
</style>
